<template>
  <div class="lovViewCont">
    <el-drawer
      v-model="drawerflag"
      :append-to-body="true"
      :before-close="closedialog"
      :size="layObj.dsize"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <template #header>
        <div class="header_title">{{ lovViewObj.lovViewTitle }}</div>
        <div class="operation_btn drawer_btn">
          <el-button @click="closedialog">{{ t('keys.cancel') }}</el-button>
          <el-button v-if="!props.Preview" type="primary" @click="submitForm('drawerform')">
            {{ t('keys.confirm') }}
          </el-button>
        </div>
      </template>
      <div class="demo-drawer__content" v-if="selectlists.length > 0 || columnLists.length > 0">
        <el-form
          ref="drawerforms"
          :model="drawerform"
          label-position="left"
          label-width="100px"
          @submit.prevent
          @keyup.enter="queryList"
          v-if="selectlists.length > 0"
        >
          <el-row :gutter="12">
            <template v-for="(item, index) in drawerform.lovViewLineList">
              <el-col :span="layObj.dspan" :key="index" v-if="item.selectFlag && selectlists.length > 0">
                <el-form-item :prop="item.fieldCode">
                  <template #label>
                    <baseLable :label="item.fieldName"></baseLable>
                  </template>
                  <template #default>
                    <!-- 文本 TEXT-->
                    <el-input
                      v-if="item.fieldType == 'TEXT'"
                      style="width：100%"
                      v-model.trim="item.fieldNamevalue"
                      :placeholder="t('keys.pleaseEnter')"
                      clearable
                    ></el-input>
                    <!-- 日期 DATE-->
                    <el-date-picker
                      style="width: 100%"
                      v-else-if="item.fieldType == 'DATE'"
                      v-model="item.fieldNamevalue"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :placeholder="t('keys.please_select_date_tips')"
                      clearable
                    >
                    </el-date-picker>
                    <!-- 日期时间 DATETIME-->
                    <el-date-picker
                      style="width: 100%"
                      v-else-if="item.fieldType == 'DATETIME'"
                      v-model="item.fieldNamevalue"
                      type="datetime"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :placeholder="t('keys.please_select_datetime_tips')"
                      clearable
                    ></el-date-picker>
                    <!-- 值集 LOV-->
                    <lov
                      v-else-if="item.fieldType == 'LOV'"
                      v-model:value="item.fieldNamevalue"
                      :lovCode="item.lovCode"
                      @change="
                        (val) => {
                          item.fieldNamevalue = val
                          queryList()
                        }
                      "
                    ></lov>
                  </template>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
          <el-row :gutter="12">
            <el-col :span="layObj.dspan">
              <div class="btns">
                <el-button type="primary" @click="searchList">
                  {{ t('keys.filter') }}
                </el-button>
                <el-button @click="resetForm">
                  {{ t('keys.Reset') }}
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <div class="allSelect" v-if="props.checkboxFlag">
          <div class="allSelectNum">
            {{ t('keys.hasSelected') }}<span>{{ allSelection.length }}</span
            >  {{ t('keys.strip') }}
          </div>
          <!-- <div class="allSelect">
            <el-checkbox v-model="allSelectionFlag" label="只显示已选项" size="large" />
          </div> -->
        </div>

        <!-- table表格 -->
        <el-row v-if="drawerflag" class="mt10">
          <el-table
            ref="multipleTableRef"
            tooltip-effect="dark"
            :row-style="{ cursor: 'pointer' }"
            max-height="523"
            border
            row-key="id"
            v-loading="loading"
            :data="tableData"
            @row-click="rowClick"
            @selection-change="handleSelectionChange"
            @select="selectClick"
            @select-all="selectAllClick"
          >
            <el-table-column
              v-if="props.checkboxFlag"
              type="selection"
              align="center"
              :reserve-selection="reserveSelection"
              :selectable="selected"
              width="48px"
            ></el-table-column>
            <el-table-column align="center" label="" width="48px" v-else>
              <template #default="scope">
                <!-- <el-radio v-model="radio" :label="scope.row.id" @change="radioChange"></el-radio> -->
                <el-radio v-model="radio" :label="scope.$index + 1" @change.native="radioChange(scope.row)"></el-radio>
              </template>
            </el-table-column>
            <template v-for="(info, index) in lovViewObj.lovViewLineList">
              <el-table-column
                show-overflow-tooltip
                :key="index"
                :label="info.fieldName"
                :prop="info.fieldCode"
                :width="info.columnWidth"
                v-if="info.columnFlag && columnLists.length > 0"
              >
              </el-table-column>
            </template>
          </el-table>
        </el-row>
        <div style="margin: 20px 0px; display: flex; justify-content: center;" v-if="lovViewObj.pageFlag">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="searchValue.totle"
            :pager-count="5"
            :page-sizes="store.state.apps.pageSizes"
            :page-size="searchValue.size"
            :current-page="searchValue.page"
            @size-change="sizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>
      <div class="demo-drawer__content" v-else>
        <el-empty  :description="t('keys.table_empty_text')"></el-empty>
      </div>
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getTenantId } from 'utils/headerToken'
import { getlovViewCodeInfo, getlovinfo, getlovList } from 'src/api/common'
import lov from '@/components/lov'
import baseLable from '@/components/base-lable'
import { ERR_OK } from 'config/statusCode'
import { useStore } from 'vuex'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 中英文

const store = useStore()
const emit = defineEmits(['lovChange'])

const props = defineProps({
  lovViewCode: {
    // 值集视图编码
    type: String,
    default: ''
  },
  Preview: {
    // 是否是预览
    type: Boolean,
    default: false
  },
  params: {
    // 父级传过来的接口参数
    type: Object,
    default: () => {}
  },
  echoedKey: {
    // 表单回显的key 字段名
    type: String,
    default: ''
  },
  allSelectList: {
    // 回显选中的数组
    type: Array, //[{id:1}]
    default: () => []
  },
  disabledList: {
    // 只有多选的时候才能禁用
    //禁用选项
    type: Array, //[{id:1}]
    default: () => []
  },
  confirmationPrompt: {
    // 是否是预览
    type: Boolean,
    default: false
  },
  checkboxFlag: {
    // 是否是单选多选默认单选  false单选   true 多选
    type: Boolean,
    default: false
  }
})

const drawerflag = ref(false)
const lovViewObj = reactive({
  // 初始化数据
  lovViewTitle: t('keys.lovView')
})
const drawerform = reactive({
  // 绑定表单
  lovViewLineList: []
})
const searchValue = reactive({
  // 搜索传值
  totle: 0,
  page: 1,
  size: 10
})
const lovInfo = reactive({}) // 获取分页接口存值
const multipleTableRef = ref(null) // table ref
const multipleSelection = ref([]) // 多选选中的list
const tableData = ref([]) // 表格数据
const radio = ref(0) // 单选数据
const selectlists = ref([]) // 搜索渲染数据
const columnLists = ref([]) // 表格渲染数据
let otherParams = reactive({}) // 接口请求的全部参数
const reserveSelection = ref(false) // 是否支持跨页勾选
const allSelectionFlag = ref(false) // 只显示已选项
const allSelection = ref([]) // 父组件传的选中的list
const layObj = reactive({ dsize: '', dspan: '' })
radio.value = 0
// 关闭弹板
const closedialog = () => {
  radio.value = 0
  allSelection.value = []
  searchValue.page = 1
  multipleSelection.value = []
  reserveSelection.value = false
  drawerflag.value = false
}
const disList = ref([])
//禁用表格选项
const selected = (row) => {
  if (disList.value.includes(row.id)) {
    return false //不可选择
  } else {
    return true //可选择
  }
}

// 初始化显示弹板获取渲染list、获取url值集接口和接受父级页面参数
const showDrawer = async (params = {}) => {
  // 初始化调用此方法
  otherParams.value = params
  // 初始化选中的数组
  if (Array.isArray(props.allSelectList)) {
    allSelection.value = props.allSelectList
  } else {
    allSelection.value = [props.allSelectList]
  }
  disList.value = []
  props.disabledList.forEach((item, index) => {
    disList.value.push(item.id)
  })

  let Url = `/v1/${getTenantId()}/lov-view/info`
  const { code, data } = await getlovViewCodeInfo({}, Url, props.lovViewCode)
  if (code === ERR_OK) {
    Object.assign(lovViewObj, data || {})
    if (JSON.stringify(lovViewObj) != '{}') {
      // 值集视图基本信息
      lovViewObj.lovViewLineList.sort(objectSort('fieldSort')).forEach((item) => {
        item.fieldNamevalue = ''
      })
      // 搜索渲染数据
      selectlists.value = lovViewObj.lovViewLineList.filter((item) => {
        return item.selectFlag
      })
      // 表格渲染数据
      columnLists.value = lovViewObj.lovViewLineList.filter((item) => {
        return item.columnFlag
      })
      // 提交表单 重置表单使用
      drawerform.lovViewLineList = JSON.parse(JSON.stringify(lovViewObj.lovViewLineList))

      initobtain()
      getlovoptions()
      // drawerflag.value = true
    } else {
      lovViewObj.lovViewTitle =  t('keys.lovView')
      drawerflag.value = true
    }
  }
}
defineExpose({ showDrawer })
// 列表数据排序
const objectSort = (property) => {
  return function(Obj1, Obj2) {
    return Obj1[property] - Obj2[property]
  }
}
// 获取下拉框的选择项数据 url值集
const getlovoptions = async () => {
  // 下拉框公共接口
  let Url = `/v1/${getTenantId()}/lov/info`
  const { code, data } = await getlovinfo({}, Url, lovViewObj.lovCode)
  if (code === ERR_OK) {
    Object.assign(lovInfo, data || {})
    if (!lovInfo.url) {
      ElMessage({
        showClose: true,
        message:  `${ t('keys.lovView')}${ t('keys.non_existent')}`,
        type: 'warning'
      })
      return
    }
    if (JSON.stringify(lovInfo) != '{}' && lovInfo.serviceCode && lovInfo.url) {
      if (!lovViewObj.delayedFlag) {
        // 判断是否是延时加载列表
        queryList()
      }
    }
  }
}

const loading = ref(false)
const queryList = async () => {
  if (!lovInfo.url) {
    ElMessage({
      showClose: true,
      message: `${ t('keys.lovView')}${ t('keys.non_existent')}`,
      type: 'warning'
    })
    return
  }
  loading.value = true
  drawerform.lovViewLineList.forEach((ele) => {
    if (ele.selectFlag) {
      drawerform[ele.fieldCode] = ele.fieldNamevalue
    }
  })

  let searchObj = { ...searchValue, ...JSON.parse(JSON.stringify(drawerform)), ...props.params, ...otherParams.value }
  delete searchObj.lovViewLineList

  let url = lovInfo.url.replace('{tenantId}', getTenantId())
  url = url.indexOf('{tenantId}') != -1 ? url.replace('{tenantId}', 0) : url
  let searchUrl = `/${lovInfo.serviceCode}${url}`.replace('/', '/$')
  reserveSelection.value = false

  const { code, data } = await getlovList(searchUrl, JSON.parse(JSON.stringify(searchObj)))
  if (code === ERR_OK) {
    if (lovViewObj.pageFlag) {
      // 判断是否支持分页
      if (data?.list) {
        searchValue.totle = data.total || 0
        tableData.value = data.list || []
        // if (lovViewObj.checkboxFlag) {
        if (props.checkboxFlag) {
          // 多选回显
          if (allSelection.value.length > 0) {
            reserveSelection.value = true
          }
          if (allSelection.value.length > 0 && tableData.value.length > 0) {
            // 更新allSelection.value中的数据 为tableData.value的新值
            allSelection.value.forEach((item1, index) => {
              const res = tableData.value.filter((item2) => {
                return item2.id == item1.id // 找到id一样的item
              })
              res[0] && allSelection.value.splice(index, 1, res[0]) // 找到一样的item后，进行替换（B的值替换A的值）
            })
            tableData.value.map((item) => {
              if (allSelection.value.find((v) => item.id === v.id)) {
                nextTick(() => {
                  multipleTableRef.value.toggleRowSelection(item, true)
                })
              }
            })
          }
        } else {
          // 单选回显
          nextTick(() => {
            radio.value = 0
            tableData.value.forEach((item1, index) => {
              if (allSelection.value.length == 1 && item1.id == allSelection.value[0].id) {
                radio.value = index + 1
              }
            })
          })
        }
      } else {
        ElMessage({
          showClose: true,
          message: t('keys.Incorrect_configuration'),
          type: 'warning'
        })
      }
    } else {
      if (Array.isArray(data) == true) {
        // 判断是否支持分页
        tableData.value = data || []
      } else {
        ElMessage({
          showClose: true,
          message:  t('keys.Incorrect_configuration'),
          type: 'warning'
        })
      }
    }
  }
  loading.value = false
}

const radioChange = (row) => {
  radio.value = 0
  tableData.value.forEach((item1, index) => {
    if (allSelection.value.length == 1 && item1.id == allSelection.value[0].id) {
      radio.value = index + 1
    }
  })
  allSelection.value = [row]
}

const resetForm = () => {
  // 重置
  drawerform.lovViewLineList.forEach((item) => {
    item.fieldNamevalue = ''
  })
  searchList()
}

const searchList = () => {
  searchValue.page = 1
  queryList()
}
const sizeChange = (val) => {
  searchValue.page = 1
  searchValue.size = val
  queryList()
}
const handleCurrentChange = (val) => {
  searchValue.page = val
  queryList()
}

let indexArr = []
const selectAllClick = (selection) => {
  indexArr = []
  for (let i = 0; i < tableData.value.length; i++) {
    // 禁用的不参与操作
    if (!disList.value.includes(tableData.value[i].id)) {
      const Index = allSelection.value.findIndex((item) => {
        return item.id == tableData.value[i].id
      })
      indexArr.push(Index) // 0、1、-1、-1、-1
      // 前两个数据的key值相同，打印出对应的下标 ，后面找不相同的key  输出-1
    }
  }
  if (indexArr.includes(-1)) {
    // 全选
    tableData.value.forEach((item) => {
      // 禁用的不参与操作
      if (!disList.value.includes(item.id)) {
        let index = allSelection.value.findIndex((v) => {
          return v.id === item.id
        })
        if (index == -1) {
          allSelection.value.push(item)
        }
      }
    })
  } else {
    // 全取消
    for (var i = 0; i < tableData.value.length; i++) {
      // 禁用的不参与操作
      if (!disList.value.includes(tableData.value[i].id)) {
        for (var j = 0; j < allSelection.value.length; j++) {
          if (allSelection.value[j].id === tableData.value[i].id) {
            allSelection.value.splice(j, 1)
            j = j - 1
          }
        }
      }
    }
  }
}

const selectClick = (selection, row) => {
  let findex = allSelection.value.findIndex((item) => {
    return item.id === row.id
  })
  if (findex !== -1) {
    allSelection.value.splice(findex, 1)
  } else {
    allSelection.value.push(row)
  }
}
const rowClick = (row, column, event) => {
  if (disList.value.includes(row.id)) return //禁用的不可点击
  // 判断时单选还是多选 checkboxFlag= true  多选
  if (props.checkboxFlag) {
    if (allSelection.value.find((item) => row.id === item.id)) {
      multipleSelection.value.splice(
        multipleSelection.value.findIndex((item) => {
          return item.id === row.id
        }),
        1
      )
      allSelection.value.splice(
        allSelection.value.findIndex((item) => {
          return item.id === row.id
        }),
        1
      )
      multipleTableRef.value.toggleRowSelection(row, false)
    } else {
      allSelection.value.push(row)
      multipleSelection.value.push(row)
      multipleTableRef.value.toggleRowSelection(row, true)
    }
    // handleSelectionChange(row)
  } else {
    radio.value = 0
    tableData.value.forEach((item1, index) => {
      if (item1.id == row.id) {
        radio.value = index + 1
      }
    })
    allSelection.value = [row]
  }
}
// 点击选中行
const handleSelectionChange = (row) => {
  // 禁用的不参与操作
  if (!disList.value.includes(row?.id)) {
    if (Array.isArray(row)) {
      multipleSelection.value = row
    } else {
      if (multipleSelection.value.find((item) => row.id === item.id)) {
        multipleSelection.value.splice(
          multipleSelection.value.findIndex((item) => {
            return item.id === row.id
          }),
          1
        )
        multipleTableRef.value.toggleRowSelection(row, false)
      } else {
        multipleSelection.value.push(row)
        multipleTableRef.value.toggleRowSelection(row, true)
      }
    }
  }
}
const submitForm = () => {
  let showFieldkey
  // let showFieldStr = ''
  let valueFieldArr = []
  // let changeValue = allSelection.value

  // 判断时单选还是多选 checkboxFlag= true  多选
  if (props.checkboxFlag) {
    showFieldkey = lovViewObj.lovViewLineList.filter((item) => {
      return item.showFieldFlag
    })
    // if (showFieldkey.length > 0) {
    //   changeValue.forEach((ele) => {
    //     changeValue.length > 1 ? (showFieldStr += ele[showFieldkey[0].fieldCode] + ',') : (showFieldStr += ele[showFieldkey[0].fieldCode])
    //   })
    //   showFieldStr = showFieldStr.substring(0, showFieldStr.length - 1)
    // }
    valueFieldArr = lovViewObj.lovViewLineList.filter((item) => {
      return item.valueFieldFlag
    })
    if (allSelection.value.length == 0) {
      ElMessage.warning(t('keys.please_select_table_line'))
      return false
    }
    // emit(,选中的数组，值字段，显示字段,父组件传显示字段/值字段)
    emit('lovChange', allSelection.value, showFieldkey[0]?.fieldCode || '', valueFieldArr[0]?.fieldCode || '', props.echoedKey)
  } else {
    showFieldkey = lovViewObj.lovViewLineList.filter((item) => {
      return item.showFieldFlag
    })
    // if (showFieldkey.length > 0) {
    //   showFieldStr = showFieldkey[0].fieldCode || ''
    // }
    valueFieldArr = lovViewObj.lovViewLineList.filter((item) => {
      return item.valueFieldFlag
    })
    if (allSelection.value.length == 0) {
      ElMessage.warning(t('keys.please_select_table_line'))
      return false
    }
    // emit(,选中的数组，值字段，显示字段,父组件传显示字段/值字段)
    emit('lovChange', allSelection.value[0], showFieldkey[0]?.fieldCode || '', valueFieldArr[0]?.fieldCode || '', props.echoedKey)
    // emit('lovChange', allSelection.value[0], showFieldStr, props.echoedKey)
  }
  multipleSelection.value = []
  radio.value = 0
  allSelection.value = []
  searchValue.page = 1
  drawerflag.value = false
}

const initobtain = () => {
  // 计算布局SMALL 小  MIDDLE=中   LARGE=大
  if (lovViewObj.lovViewSize == 'SMALL') {
    layObj.dsize = '800px'
    layObj.dspan = 12
  } else {
    layObj.dsize = '1160px'
    layObj.dspan = 8
  }
  drawerflag.value = true
}
</script>
<style lang="scss" scoped>
.lovViewCont {
  z {
    font-size: 16px;
    font-weight: 550;
  }
  .formlabel {
    display: inline-flex;
  }
  .searchBtns {
    margin-bottom: 16px;
  }
  .operation_btn.drawer_btn {
    text-align: right;
  }
  .el-form-item {
    margin-bottom: 8px;
  }
  :deep(.el-table) {
    th {
      .cell {
        white-space: nowrap !important;
        text-overflow: ellipsis;
        word-break: break-all;
      }
    }
  }
  :deep(.el-radio__label) {
    display: none;
  }
  .demo-drawer__content {
    margin-bottom: 60px;
  }
}
:deep(.allSelect) {
  display: flex;
  flex-direction: row;
  align-items: center;
  line-height: 40px;
  .allSelectNum {
    color: #666666;
    margin-right: 20px;
    font-size: 14px;
    span {
      margin: 0 5px;
      color: var(--el-color-primary);
    }
  }
}
:deep(.el-radio__label) {
  display: none;
}

.btns {
  margin-bottom: 10px;
}
</style>
